package org.jeecg.modules.outbound.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.erp.base.entity.ErpWarehouse;
import org.jeecg.modules.erp.base.service.IErpWarehouseService;
import org.jeecg.modules.outbound.entity.BussOutboundOrderDetail;
import org.jeecg.modules.outbound.service.IBussOutboundOrderDetailService;
import org.jeecg.modules.outbound.vo.BussOutboundOrderDetailVo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.outbound.entity.BussOutboundOrderInformation;
import org.jeecg.modules.outbound.entity.BussOutboundOrderManagement;
import org.jeecg.modules.outbound.vo.BussOutboundOrderManagementPage;
import org.jeecg.modules.outbound.service.IBussOutboundOrderManagementService;
import org.jeecg.modules.outbound.service.IBussOutboundOrderInformationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 出库单管理
 * @Author: jeecg-boot
 * @Date:   2024-06-18
 * @Version: V1.0
 */
@Api(tags="出库单管理")
@RestController
@RequestMapping("/outbound/bussOutboundOrderManagement")
@Slf4j
public class BussOutboundOrderManagementController {
	@Autowired
	private IBussOutboundOrderManagementService bussOutboundOrderManagementService;
	@Autowired
	private IBussOutboundOrderInformationService bussOutboundOrderInformationService;
	@Autowired
	private IBussOutboundOrderDetailService bussOutboundOrderDetailService;
	
	/**
	 * 分页列表查询
	 *
	 * @param bussOutboundOrderManagement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "出库单管理-分页列表查询")
	@ApiOperation(value="出库单管理-分页列表查询", notes="出库单管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BussOutboundOrderManagement>> queryPageList(BussOutboundOrderManagement bussOutboundOrderManagement,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BussOutboundOrderManagement> queryWrapper = QueryGenerator.initQueryWrapper(bussOutboundOrderManagement, req.getParameterMap());
		Page<BussOutboundOrderManagement> page = new Page<BussOutboundOrderManagement>(pageNo, pageSize);
		IPage<BussOutboundOrderManagement> pageList = bussOutboundOrderManagementService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param bussOutboundOrderManagementPage
	 * @return
	 */
	@AutoLog(value = "出库单管理-添加")
	@ApiOperation(value="出库单管理-添加", notes="出库单管理-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BussOutboundOrderManagementPage bussOutboundOrderManagementPage) {
		if (bussOutboundOrderManagementPage.getOutboundOrderDetailList() == null || bussOutboundOrderManagementPage.getOutboundOrderDetailList().size()<1){
				return Result.error("请勾选出库的库存明细！");
		}
		BussOutboundOrderManagement bussOutboundOrderManagement = new BussOutboundOrderManagement();
		BeanUtils.copyProperties(bussOutboundOrderManagementPage, bussOutboundOrderManagement);
		bussOutboundOrderManagementService.saveMain(bussOutboundOrderManagement, bussOutboundOrderManagementPage.getBussOutboundOrderInformationList(),bussOutboundOrderManagementPage.getOutboundOrderDetailList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param bussOutboundOrderManagementPage
	 * @return
	 */
	@AutoLog(value = "出库单管理-编辑")
	@ApiOperation(value="出库单管理-编辑", notes="出库单管理-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BussOutboundOrderManagementPage bussOutboundOrderManagementPage) {
		if (bussOutboundOrderManagementPage.getOutboundOrderDetailList() == null || bussOutboundOrderManagementPage.getOutboundOrderDetailList().size()<1){
			return Result.error("请勾选出库的库存明细！");
		}
		BussOutboundOrderManagement bussOutboundOrderManagement = new BussOutboundOrderManagement();
		BeanUtils.copyProperties(bussOutboundOrderManagementPage, bussOutboundOrderManagement);
		BussOutboundOrderManagement bussOutboundOrderManagementEntity = bussOutboundOrderManagementService.getById(bussOutboundOrderManagement.getId());
		if(bussOutboundOrderManagementEntity==null) {
			return Result.error("未找到对应数据");
		}
		bussOutboundOrderManagementService.updateMain(bussOutboundOrderManagement, bussOutboundOrderManagementPage.getBussOutboundOrderInformationList(),bussOutboundOrderManagementPage.getOutboundOrderDetailList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库单管理-通过id删除")
	@ApiOperation(value="出库单管理-通过id删除", notes="出库单管理-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		bussOutboundOrderManagementService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出库单管理-批量删除")
	@ApiOperation(value="出库单管理-批量删除", notes="出库单管理-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bussOutboundOrderManagementService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库单管理-通过id查询")
	@ApiOperation(value="出库单管理-通过id查询", notes="出库单管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BussOutboundOrderManagement> queryById(@RequestParam(name="id",required=true) String id) {
		BussOutboundOrderManagement bussOutboundOrderManagement = bussOutboundOrderManagementService.getById(id);
		if(bussOutboundOrderManagement==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(bussOutboundOrderManagement);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库单信息通过主表ID查询")
	@ApiOperation(value="出库单信息主表ID查询", notes="出库单信息-通主表ID查询")
	@GetMapping(value = "/queryBussOutboundOrderInformationByMainId")
	public Result<List<BussOutboundOrderInformation>> queryBussOutboundOrderInformationListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussOutboundOrderInformation> bussOutboundOrderInformationList = bussOutboundOrderInformationService.selectByMainId(id);
		return Result.OK(bussOutboundOrderInformationList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库单明细通过主表ID查询")
	@ApiOperation(value="出库单明细主表ID查询", notes="出库单明细-通主表ID查询")
	@GetMapping(value = "/queryOutboundOrderDetailByMainId")
	public Result<List<BussOutboundOrderDetailVo>> queryOutboundOrderDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussOutboundOrderDetailVo> outboundOrderDetailList =  bussOutboundOrderDetailService.selectByMainId(id);
		return Result.OK(outboundOrderDetailList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param bussOutboundOrderManagement
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BussOutboundOrderManagement bussOutboundOrderManagement) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<BussOutboundOrderManagement> queryWrapper = QueryGenerator.initQueryWrapper(bussOutboundOrderManagement, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<BussOutboundOrderManagement> bussOutboundOrderManagementList = bussOutboundOrderManagementService.list(queryWrapper);

      // Step.3 组装pageList
      List<BussOutboundOrderManagementPage> pageList = new ArrayList<BussOutboundOrderManagementPage>();
      for (BussOutboundOrderManagement main : bussOutboundOrderManagementList) {
          BussOutboundOrderManagementPage vo = new BussOutboundOrderManagementPage();
          BeanUtils.copyProperties(main, vo);
          List<BussOutboundOrderInformation> bussOutboundOrderInformationList = bussOutboundOrderInformationService.selectByMainId(main.getId());
          vo.setBussOutboundOrderInformationList(bussOutboundOrderInformationList);
		  List<BussOutboundOrderDetailVo> outboundOrderDetailList = new ArrayList<>();
		  //outboundOrderDetailService.selectByMainId(id);
          vo.setOutboundOrderDetailList(outboundOrderDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "出库单管理列表");
      mv.addObject(NormalExcelConstants.CLASS, BussOutboundOrderManagementPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单管理数据", "导出人:"+sysUser.getRealname(), "出库单管理"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BussOutboundOrderManagementPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BussOutboundOrderManagementPage.class, params);
              for (BussOutboundOrderManagementPage page : list) {
                  BussOutboundOrderManagement po = new BussOutboundOrderManagement();
                  BeanUtils.copyProperties(page, po);
                  bussOutboundOrderManagementService.saveMain(po, page.getBussOutboundOrderInformationList(),page.getOutboundOrderDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 @ApiOperation(value="根据id查询打印预览需要的数据", notes="根据id查询打印预览需要的数据")
	 @GetMapping(value = "/getPrintViewData/{id}")
	 public Result<List> getPrintViewData(@PathVariable("id") String id) {
		 ArrayList<Map<String, Object>> maps = new ArrayList<>();
		 Map<String, Object> map = new HashMap<>();
		 map.put("title","出库单");
		 map.put("templateId","978885860275281920");
		 map.put("id",id);
		 map.put("infoTable","buss_outbound_order_information");
		 map.put("table","buss_outbound_order_management");
//		 HashMap<String, Object> inMap = new HashMap<>();
//		 BussOutboundOrderManagement bussOutboundOrderManagement = bussOutboundOrderManagementService.selectForPrint(id);
//		 inMap.put("code",bussOutboundOrderManagement.getCode());
//		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//		 inMap.put("outboundDate",sdf.format(bussOutboundOrderManagement.getCreateTime()));
//		 inMap.put("nowDate",sdf.format(new Date()));
//		 inMap.put("createByName",bussOutboundOrderManagement.getCreateBy());
//		 inMap.put("warehouse",bussOutboundOrderManagement.getWarehouseId());
//		 inMap.put("remark",bussOutboundOrderManagement.getRemark());
//		 inMap.put("workshop",bussOutboundOrderManagement.getDepartmentWorkshop());
//		 inMap.put("outboundType",bussOutboundOrderManagement.getOutboundType());
//
//		 List<BussOutboundOrderDetail> outboundOrderDetailList =  bussOutboundOrderDetailService.selectForPrint(id);
//		 inMap.put("detail",outboundOrderDetailList);
//		 map.put("data",inMap);
		 maps.add(map);
		 return Result.OK(maps);
	 }

	 @GetMapping("/revokeBatch")
	 public Result<String> revokeBatch(@RequestParam(name="ids",required=true) String ids){
		 this.bussOutboundOrderManagementService.revokeBatch(Arrays.asList(ids.split(",")));
		 return Result.OK("撤回成功");
	 }
}
